import { debounceGol } from '@/system/utils/commonUtils';
import { useAppStore } from '@/stores/app';
import { nextTick, reactive, ref, toRaw, toRefs, toValue, watch } from 'vue';
let appStore = null;

function getAppStore() {
    if (!appStore) {
        appStore = useAppStore();
    }
    return appStore;
}

/**
 * TODO(监听窗口变化)
 * @auther zhangQ
 * @date 2018/8/23 20:39
 */
export function windowHeightFun() {
    let wh = window.innerHeight || (document.documentElement && document.documentElement.clientHeight) || document.body.clientHeight;
    // store.dispatch('setWindowHeight', wh);
    getAppStore().setWindowHeight(wh);
}

export const globalMixins = {
    //直接在main.js中定义
    // data() {
    //   return { resizeHeightCallBack: [] };
    // },
    computed: {
        resizeHeight() {
            return getAppStore().windowHeight;
        },
    },
    watch: {
        resizeHeight(val) {
            this.resizeHtightDebounce && this.resizeHtightDebounce(val, this.resizeHeightCallBack);
        },
    },
    // beforeUnmount() {
    //     if (this._eventBusNameMap) {
    //         for (const argumentsKey in this._eventBusNameMap) {
    //             evnetBus.$off(argumentsKey);
    //         }
    //         this._eventBusNameMap = undefined;
    //     }
    // },
    unmounted() {},
    methods: {
        // _eventBusOnReg(eventName, fun) {
        //     if (!this._eventBusNameMap) {
        //         this._eventBusNameMap = {};
        //     }
        //     this._eventBusNameMap[eventName] = fun;
        //     evnetBus.$on(eventName, fun);
        // },
        _resizeHeightWatch(callBack) {
            // 减去菜单高度
            callBack(this.resizeHeight - 30);
            if (!this.resizeHeightCallBack) {
                this.resizeHtightDebounce = debounceGol(this._resizeHtightHandle, 200);
                this.resizeHeightCallBack = [];
            }
            this.resizeHeightCallBack.push(callBack);
        },
        _resizeHtightHandle(val, resizeHeightCallBack) {
            if (resizeHeightCallBack && resizeHeightCallBack.length > 0) {
                for (let i = 0; i < resizeHeightCallBack.length; i++) {
                    if (typeof resizeHeightCallBack[i] === 'function') {
                        console.log('resizeHeight', val);
                        // 减去菜单高度
                        resizeHeightCallBack[i](val - 25);
                    }
                }
            }
        },
        /**
         * localStorage 对象缓存
         * @param lsKey 对象key
         * @param key 对象key
         * @param def 默认值
         * @returns 返回缓存的值
         * @private
         */
        async _addLocalStorageListenObj({ cacheKey, watchKey, defaultVal = {}, onChange = undefined }) {
            const defClone = defaultVal;
            let cacheVal = defaultVal;
            // console.log('localStorage.getItem(lsKey)', localStorage.getItem(lsKey));
            try {
                let res = await window.jsonStorage.getJsonCache('cache_' + cacheKey);
                if (res) {
                    cacheVal = res;
                }
                watch(
                    watchKey,
                    (newV, oldV) => {
                        window.jsonStorage.writeJsonCache('cache_' + cacheKey, toRaw(newV)).then();
                        onChange && onChange(newV);
                    },
                    { deep: true },
                );
            } catch (e) {
                console.log('_addLocalStorageListenObj', cacheKey, '错误:', e);
                cacheVal = defClone;
                // this.$set(this, key, cacheVal);
            } finally {
                let watchData = watchKey();
                for (let cacheValKey in cacheVal) {
                    watchData[cacheValKey] = cacheVal[cacheValKey];
                }
            }
        },
        /**
         * localStorage 对象缓存
         * @param lsKey 对象key
         * @param key 对象key
         * @param def 默认值
         * @param expSj 固定过期时间
         * @returns 返回缓存的值
         * @private
         */
        async _getLocalStorageObjExp(lsKey, key, def, expSj) {
            let cacheVal = Object.assign({}, def || {});
            try {
                let res = await window.jsonStorage.getJsonCache('cache_' + lsKey);
                if (res) {
                    if (res._expSj && +Date.now() > +res._expSj) {
                        // 如果过期就取默认值
                        await window.jsonStorage.deleteJsonCacheByKey('cache_' + lsKey);
                    } else {
                        cacheVal = res;
                    }
                }
            } catch (e) {
                console.error('_getLocalStorageObjExp.error:', lsKey, e);
            }
            return cacheVal;
        },

        /**
         * localStorage 对象缓存
         * @param lsKey 对象key
         * @param key 对象key
         * @param def 默认值
         * @param expSj 固定过期时间
         * @returns 返回缓存的值
         * @private
         */
        async _addLocalStorageObjExp(lsKey, newV, expSj) {
            try {
                let saveData = toRaw(newV);
                if (expSj) {
                    saveData._expSj = +Date.now() + +expSj * 60 * 1000;
                } else {
                    // 默认缓存时间3分钟
                    saveData._expSj = +Date.now() + +3 * 60 * 1000;
                }
                await window.jsonStorage.writeJsonCache('cache_' + lsKey, saveData);
            } catch (e) {
                console.error('_addLocalStorageObjExp.error:', lsKey, e);
            }
        },
        /**
         * 添加绑定字符对象缓存到 localStorage
         * @param lsKey 缓存的key值
         * @param key 缓存data对象的key值,如果是对象则[对象.key]
         * @param def 默认值
         * @param parentData 上机对象,为空则是 this
         * @returns {string}
         * @private
         */
        async _addLocalStorageListenStr(lsKey, key, def, parentData) {
            this.$watch(key, (newV) => {
                window.jsonStorage.writeJsonCache('cache_' + lsKey, newV);
            });
            let cacheVal = (await window.jsonStorage.getJsonCache('cache_' + lsKey)) || def;
            console.log('_addLocalStorageListenStr:cacheVal', cacheVal);
            this.$set(parentData || this, key, cacheVal);
            return cacheVal;
        },
        /**
         * localStorage 对象缓存
         * @param lsKey 对象key
         * @param key 对象key
         * @param def 默认值
         * @param expSj 固定过期时间
         * @returns 返回缓存的值
         * @private
         */
        async _addLocalStorageListenObjExp(lsKey, key, def, expSj) {
            const defClone = Object.assign({}, def || {});
            let cacheVal = defClone;
            // console.log('localStorage.getItem(lsKey)', localStorage.getItem(lsKey));
            try {
                let res = await window.jsonStorage.getJsonCache('cache_' + lsKey);
                if (res) {
                    cacheVal = res;
                    if (cacheVal._expSj) {
                        // 如果过期就取默认值
                        if (+Date.now() > +cacheVal._expSj) {
                            await window.jsonStorage.deleteJsonCacheByKey('cache_' + lsKey);
                            cacheVal = def;
                        }
                    }
                    this.$set(this, key, cacheVal);
                }
                this.$nextTick(() => {
                    this.$watch(key, {
                        async handler(newV) {
                            // localStorage.setItem(lsKey, JSON.stringify(newV));
                            if (!newV._expSj && expSj) {
                                newV._expSj = +Date.now() + +expSj * 60 * 1000;
                            }
                            await window.jsonStorage.writeJsonCache('cache_' + lsKey, newV);
                        },
                        deep: true,
                    });
                });
            } catch (e) {
                cacheVal = defClone;
                this.$set(this, key, cacheVal);
            }
        },
    },
};
